<template>
  <el-card class="mt-20">
    <el-form
      label-width="100px"
      ref="SPUForm"
      :rules="SPUFormRules"
      :model="SPUData"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input v-model="SPUData.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select v-model="SPUData.tmId">
          <el-option
            :value="tm.id"
            :label="tm.tmName"
            v-for="tm in trandemarkList"
            :key="tm.id"
          ></el-option>
          <el-option value="123" label="123"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          autosize
          type="textarea"
          v-model="SPUData.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          :action="`${BASE_URL}/admin/product/fileUpload`"
          v-model:file-list="SPUData.spuImageList"
          list-type="picture-card"
          :on-success="handleAvatarSuccess"
          :on-preview="handlePictureCardPreview"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
          :limit="10"
          :class="{ 'clear-plus': SPUData.spuImageList?.length >= 10 }"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          v-model="saleAttrValue"
          :placeholder="`还有 ${saleAttrComputed.length} 项未选择`"
        >
          <el-option
            :value="`${attr.id}:${attr.name}`"
            :label="attr.name"
            v-for="attr in saleAttrComputed"
            :key="attr.id"
          />
        </el-select>
        <el-button type="primary" class="ml-10" @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table :data="SPUData.spuSaleAttrList" border class="mt-20">
          <el-table-column type="index" label="序号"></el-table-column>
          <el-table-column label="属性名" prop="saleAttrName"></el-table-column>
          <el-table-column label="属性名称列表">
            <template #default="{ row, $index }">
              <el-tag
                v-for="saleAttr in row.spuSaleAttrValueList"
                :key="saleAttr.saleAttrValueName"
                class="mx-1"
                closable
                :disable-transitions="false"
                @close="handleClose(row, saleAttr.saleAttrValueName)"
              >
                {{ saleAttr.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.showNum"
                ref="InputRef"
                v-model="inputValue"
                class="ml-1 w-20"
                size="small"
                @keyup.enter="handleInputConfirm(row, $index)"
                @blur="handleInputConfirm(row, $index)"
              />
              <el-button
                v-else
                class="button-new-tag ml-1"
                size="small"
                @click="showInput(row)"
                :icon="Plus"
              >
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="{ $index }">
              <el-tooltip content="删除" effect="light" placement="top">
                <el-button
                  :icon="Delete"
                  size="small"
                  type="danger"
                  @click="delSingleAttr($index)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item class="mt-20">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="$emit('changeCom', 0)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'addSPU',
}
</script>

<script lang="ts" setup>
import { reactive, ref, onMounted, nextTick, computed } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElInput } from 'element-plus'
import type {
  UploadProps,
  FormInstance,
  FormRules,
  UploadFile,
} from 'element-plus'
import type {
  SaleAttrList,
  BaseTrandemarkList,
  SPUFromDataType2,
  TableDataType,
  SpuSaleAttrListType,
  SPUParamsType2,
  SpuImageListType,
} from '@/api/product/model/SPUType'
import {
  getBaseSaleAttrList,
  getTrandemarkList,
  addSpuInfo,
  getSpuImageList,
  getSpuSaleAttrList,
  updateSkuInfoApi,
} from '@/api/product/SPUApi'
import { useCategoryId } from '@/stores/categoryId'

const emit = defineEmits(['changeCom'])
const prop = defineProps<{ toAddSpuDataInfo: SPUFromDataType2 }>()

// 表单实例
const SPUForm = ref<FormInstance>()
// 获取category3Id
const categortStore = useCategoryId()
// 收集表单数据
// const SPUData = reactive<SPUFromDataType2>({
//   category3Id: categortStore.category3Id as number,
//   spuName: '',
//   tmId: undefined,
//   description: '',
//   spuImageList: [],
//   spuSaleAttrList: [],
// })
const SPUData = reactive<SPUFromDataType2>({
  ...prop.toAddSpuDataInfo,
  spuImageList: [],
  spuSaleAttrList: [],
  category3Id: categortStore.category3Id,
})
onMounted(async () => {
  if (!SPUData.id) return
  const spuImageList = await getSpuImageList(SPUData.id as number)
  SPUData.spuImageList = spuImageList.map((img: SpuImageListType) => ({
    name: img.imgName,
    url: img.imgUrl,
  }))
})
onMounted(async () => {
  if (!SPUData.id) return
  SPUData.spuSaleAttrList = await getSpuSaleAttrList(SPUData.id as number)
})
// 定义基本销售属性的数据
const saleAttr = ref<SaleAttrList>([])
// 定义基本品牌数据
const trandemarkList = ref<BaseTrandemarkList>([])
// 组件挂载请求数据
onMounted(async () => {
  trandemarkList.value = await getTrandemarkList()
})
onMounted(async () => {
  saleAttr.value = await getBaseSaleAttrList()
})

// 表单校验相关---------------------开始
const addValueAttr = (rule: any, value: any, callback: any) => {
  if (!value.length) {
    callback(new Error('请添加销售属性'))
    return
  }
  if (
    value.some((spuSaleAttr: SpuSaleAttrListType) => {
      return !spuSaleAttr.spuSaleAttrValueList.length
    })
  ) {
    callback(new Error('请至少添加一种销售属性'))
    return
  }
  callback()
}
const SPUFormRules = reactive<FormRules>({
  spuName: [{ required: true, message: '请输入SPU名称', trigger: 'blur' }],
  tmId: [{ required: true, message: '请输选择SPU品牌', trigger: 'change' }],
  description: [{ required: true, message: '请输入SPU描述', trigger: 'blur' }],
  spuImageList: [{ required: true, message: '请添加SPU图片', trigger: 'blur' }],
  spuSaleAttrList: [
    { required: true, message: '请添加SPU销售属性', trigger: 'blur' },
    { validator: addValueAttr, trigger: 'blur' },
  ],
})
// 表单校验相关---------------------结束

// 表单提交
const submitForm = async () => {
  await SPUForm.value?.validate(async (valid, fields) => {
    if (valid) {
      const spuImageList = SPUData.spuImageList.map((img) => {
        return {
          imgName: img.name,
          imgUrl: img.response ? (img.response as any).data : img.url,
        }
      })
      if (SPUData.id) {
        await updateSkuInfoApi({ ...SPUData, spuImageList })
        ElMessage.success('修改成功')
      } else {
        await addSpuInfo({ ...SPUData, spuImageList })
        ElMessage.success('添加成功')
      }
      emit('changeCom', 0)
    }
  })
}

// 收集销售属性ID
const saleAttrValue = ref('')
// 计算属性
const saleAttrComputed = computed(() => {
  return saleAttr.value.filter((attr) => {
    return !SPUData.spuSaleAttrList.some(
      (saleAttr) => saleAttr.baseSaleAttrId === attr.id
    )
  })
})

// 点击添加销售属性
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrValue.value.split(':')
  SPUData.spuSaleAttrList.push({
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    showNum: false,
    spuSaleAttrValueList: [],
  })
  saleAttrValue.value = ''
}
// 删除的小按钮
const delSingleAttr = (index: number) => {
  SPUData.spuSaleAttrList.splice(index, 1)
}

// table中标签的数据
const inputValue = ref('')
const InputRef = ref<InstanceType<typeof ElInput>>()

// 输入框提交数据
const handleInputConfirm = (row: TableDataType, index: number) => {
  if (inputValue.value) {
    const addObj = {
      baseSaleAttrId: row.baseSaleAttrId,
      saleAttrValueName: inputValue.value,
    }
    row.spuSaleAttrValueList.push(addObj)
  }
  if (!row.spuSaleAttrValueList.length) {
    // delSingleAttr(row)
  }
  row.showNum = false
  inputValue.value = ''
}
// 删除小标签
const handleClose = (row: TableDataType, saleAttrValueName: string) => {
  row.spuSaleAttrValueList = row.spuSaleAttrValueList.filter(
    (item) => item.saleAttrValueName != saleAttrValueName
  )
}
// 展示输入框
const showInput = (row: TableDataType) => {
  row.showNum = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

// 收集图片相关------------------————————————————————————————————————————————————----------------------------------------开始
const BASE_URL = import.meta.env.VITE_API_URL
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 图片上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile: UploadFile
) => {
  if (SPUData.spuImageList.length > 1) return // 清除表单验证
  SPUForm.value?.clearValidate(['spuImageList'])
  console.log()
}
// 图片上传之前得校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('图片格式必须是jpeg 或 png 或 jpg!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}
// 预览图片的列表
// const fileList = ref<UploadUserFile[]>([])
// 点击图片预览
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url as string
  dialogVisible.value = true
}

// 上传图片相关=-------==-===============================----------结束
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.mt-20 {
  margin-top: 20px;
}
.spu-sub-btn {
  margin-top: 20px;
}
</style>
<style>
.ml-10 {
  margin-left: 10px;
}
.w-100 {
  width: 100px;
}
.w-20 {
  width: 80px;
}
.mx-1 {
  margin: 0 2px;
}
</style>
<style>
.clear-plus .el-upload--picture-card {
  display: none;
}
</style>
